package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class ProductController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    def exportService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond Product.list(params), model: [productCount: Product.count()]
    }

    def show(Product product)
    {
        def attachmentList = Attachment.findAll("from Attachment where product.id = ?", [product.id])
        respond product, model: [attachmentList: attachmentList]
    }

    def create()
    {
        respond new Product(params)
    }

    @Transactional
    def save(Product product)
    {
        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (product.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond product.errors, view: 'create'
            return
        }

        product.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                // redirect product
                redirect(controller: "productLine", action: "show", params: [id: product?.productLine?.id])
            }
            '*' { respond product, [status: CREATED] }
        }
    }

    def edit(Product product)
    {
        respond product
    }

    @Transactional
    def update(Product product)
    {
        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (product.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond product.errors, view: 'edit'
            return
        }

        product.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                // redirect product
                redirect(controller: "productLine", action: "show", params: [id: product?.productLine?.id])
            }
            '*' { respond product, [status: OK] }
        }
    }

    @Transactional
    def delete(Product product)
    {

        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        product.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                // redirect action: "index", method: "GET"
                redirect(controller: "productLine", action: "show", params: [id: product?.productLine?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchProduct()
    {
        def name = params["name"]
        String sql = "from Product as u where 1=1"
        if (name)
        {
            sql += " and u.name like '%${name}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Product.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Product.executeQuery(countSql)

        respond list, model: [productCount: count[0], params: params], view: 'index'
    }

    def exportProduct()
    {
        def name = params["name"]
        String sql = "from Product as u where 1=1"
        if (name)
        {
            sql += " and u.name like '%${name}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Product.findAll(sql)
        def count = Product.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=product.${params.extension}")
            List fields = ["name", "specifications", "active", "createdDate", "modifiedDate"]
            Map labels = ["name": "名称", "specifications": "规格", "active": "有效性", "createdDate": "创建时间", "modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
